package com.sell.demo.entity;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.sell.demo.util.RegionCodeUtil;

/**
 * Created by Mingo on 2017/6/14.
 */
@Repository
public class RegionRepository {

    private static List<Region> regions;

    public RegionRepository() throws IOException {
        regions = new ArrayList<Region>();
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("regions.conf");
        List<String> lines = IOUtils.readLines(resourceAsStream);

        lines.forEach(line -> {
            String[] split = StringUtils.split(line);
            regions.add(new Region(split[0], split[1]));
        });
    }

    /**
     * 根据code获取区域
     * @param code
     * @return
     */
    public Region findRegionByCode(String code) {
        return regions.stream()
                .filter(region -> StringUtils.equals(region.getCode(), code))
                .findFirst().orElse(null);
    }

    /**
     * 获取省列表
     * @return
     */
    public List<Region> findAllProvince() {
        return regions.stream()
                .filter(region -> StringUtils.endsWith(region.getCode(), "0000"))
                .collect(Collectors.toList());
    }

    /**
     * 获取市列表
     * @param code 省code， 可以为空，为空返回全国城市列表
     * @return
     */
    public List<Region> findCityList(String code) {
        if (StringUtils.isEmpty(code)) {
            return regions.stream().filter(region -> RegionCodeUtil.isCity(region.getCode()))
                    .collect(Collectors.toList());
        }
        return regions.stream()
                .filter(region -> RegionCodeUtil.isCity(region.getCode()) && RegionCodeUtil.isIn(code, region.getCode()))
                .collect(Collectors.toList());
    }

    /**
     * 获取市列表
     * @param code 省市code， 可以为空，为空返回全国城市列表
     * @return
     */
    public List<Region> findCountyList(String code) {
        if (StringUtils.isEmpty(code)) {
            return regions.stream().filter(region -> RegionCodeUtil.isCounty(region.getCode()))
                    .collect(Collectors.toList());
        }
        return regions.stream()
                .filter(region -> RegionCodeUtil.isCounty(region.getCode()) && RegionCodeUtil.isIn(code, region.getCode()))
                .collect(Collectors.toList());
    }
}
